package dhz.storage.configurations;

import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class MultipartResolver extends CommonsMultipartResolver {
    static final Logger logger = LoggerFactory.getLogger(CommonsMultipartResolver.class);
    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        if(request.getRequestURL().toString().endsWith("/interface/upload")){
            logger.info("prepare for file upload!");
            FileUpload uploader = this.prepareFileUpload(super.determineEncoding(request));
            String identification = SecurityUtils.getSubject().getPrincipal().toString();
            String filename = request.getParameter("filename");
            logger.info("filename received: "+filename);
            CustomUploadListener myListener = new CustomUploadListener(identification, filename);
            uploader.setProgressListener(myListener);
            logger.info(SecurityUtils.getSubject().getPrincipal().toString()+" tries to upload file");
            try{
                List<FileItem> items = ((ServletFileUpload)uploader).parseRequest(request);
                return super.parseFileItems(items, super.determineEncoding(request));
            } catch(Exception e){
                e.printStackTrace();
            }
            myListener.close();
        }
        logger.info("Multipart Resolver Passed!");
        return super.parseRequest(request);
    }
}
